package helper

import (
	"regexp"
)

/*
RegExpVerify 正则验证入口函数
verifyStr string 需要正则匹配的字符串
regType string 匹配类型，比如 手机（mobile）、邮箱（email）等等
*/
func RegExpVerify(verifyStr string, regType string) bool {
	var funcs = map[string]func() string{
		"mobile":   mobile,
		"email":    email,
		"bankCard": bankCard,
		"idCard":   idCard,
		"telephone": telephone,
		"password": password,
		"url": urlReg,
		"crontabSwoole": crontabSwoole,
		"crontabLinux": crontabLinux,
	}
	reg := funcs[regType]()
	rst := regexp.MustCompile(reg).Match([]byte(verifyStr))
	return rst
}

// mobile 手机号正则
func mobile() string {
	return `^1[3|4|5|6|7|8|9]{1}\d{9}$`
}

// email 邮箱正则
func email() string {
	return `^\s*\w+(?:\.{0,1}[\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\.[a-zA-Z]+\s*$`
}

// bankCard 银行卡号正则
func bankCard() string {
	return `^([1-9]{1})(\d{11}|\d{15}|\d{16}|\d{17}|\d{18})$`
}

// idCard 身份证号码正则
func idCard() string {
	return `^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}(\d|x|X)$`
}

// 电话正则 格式为：XXXX-XXXXXXX，XXXX-XXXXXXXX，XXX-XXXXXXX，XXX-XXXXXXXX，XXXXXXX，XXXXXXXX
func telephone() string {
	return `/^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$/`
}

// 密码正则 密码以字母开头，长度在6-18之间，只能包含字符、数字和下划线
func password() string {
	return `/^[a-zA-Z]\w{5,17}$/`
}

// 验证是否是url
func urlReg() string {
	return `^(https|http|ftp)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(:[0-9]{1,5})?(\/[\S]*)?$`
}

// swoole 定时任务验证规则
func crontabSwoole() string {
	return `/^((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)$/i`
}

func crontabLinux() string {
	return `/^((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)$/i`
}
